<template>
  <div class="flex-center search-wrap">
    <div ref="labelWrap" class="label-wrap flex-center flex-auto">
      <div v-for="(item, index) in showList" :key="index" :ref="setItemRef" class="form-item">{{ item.label }}：{{ item.value }}</div>
      <div v-if="showMore" class="form-item">...</div>
    </div>
    <el-button-group style="flex-shrink: 0;">
      <el-button :disabled="checkEmptySearch" type="primary" plain @click="clear();search()">
        <el-icon class="font14"><svg-icon name="common-clear" /></el-icon>
        <span class="font12">
          清空筛选
        </span>
      </el-button>
      <el-popover
        ref="popoverRef"
        placement="bottom-end"
        title=""
        :width="950"
        trigger="click"
        content=""
        @hide="hideSearch"
      >
        <div class="p13" style="padding-bottom: 0 !important;">
          <SchemaForm
            ref="setSchemaFormRef"
            :fields="searchForm"
            :form-schema="selectorOption"
            label-width="70px"
            class="dialog-search-wrap"
          >
            <template v-for="item in filterSlot" :key="item.slotName" #[item.slotName]>
              <slot :name="item.slotName" />
            </template>
          </SchemaForm>
          <div class="search-footer">
            <el-button size="small" type="primary" @click="search">搜索</el-button>
            <el-button size="small" cancel @click="clear">清空</el-button>
          </div>
        </div>
        <template #reference>
          <el-button class="ml2" type="primary" plain :icon="searchWindowShow ? ArrowUp : ArrowDown" @click="searchWindowShow = !searchWindowShow" />
        </template>
      </el-popover>
    </el-button-group>
  </div>
</template>

<script setup>
import { ArrowDown, ArrowUp } from '@element-plus/icons-vue'
import { computed, nextTick, onMounted, watch } from 'vue'
import { deepClone } from '@/util'
import { isObject } from 'lodash-es'

const emit = defineEmits(['search', 'clear'])
const props = defineProps({
  formConfig: {
    required: true,
    type: Array
  },
  defaultForm: {
    type: Object,
    default() {
      return {}
    }
  }
})

const setSchemaFormRef = ref(null)
const searchForm = ref(Object.assign({}, props.defaultForm))
const cacheForm = ref({})
const showList = ref([])
const searchWindowShow = ref(false)
const refs = ref([])
const labelWrap = ref(null)
const popoverRef = ref(null)
const wrapWidth = ref(0)
const showMore = ref(false)

watch(() => props.defaultForm, val => {
  Object.assign(searchForm.value, val)
}, { deep: true })

const checkEmptySearch = computed(() => {
  let flag = true
  for (const key in searchForm.value) {
    if (searchForm.value[key]) {
      flag = false
    }
  }
  return flag
})

const selectorOption = computed(() => {
  const formList = deepClone(props.formConfig)

  formList.forEach(item => {
    if (item.attr) {
      item.attr.popperClass = 'selectSmallText'
      item.attr.teleported = false
    }
  })
  return [
    ...formList
  ]
})

const filterSlot = computed(() => {
  return props.formConfig.filter(item => item.type === 'slot')
})

function hideSearch() {
  searchWindowShow.value = false
}

function setItemRef(el) {
  if (el) {
    refs.value.push(el)
  }
}

function init() {
  clear()
  // props.formConfig.forEach(item => {
  //   if (item.showDialog) {
  //     showList.value.push({
  //       label: item.props.label,
  //       value: '全部'
  //     })
  //   }
  // })
}

function search() {
  const temp = []
  refs.value = []
  showMore.value = false
  popoverRef.value.hide()
  searchWindowShow.value = false
  props.formConfig.forEach(item => {
    if (item.props.label) {
      if (item.type === 'date-picker' && item.attr.type === 'daterange' && Array.isArray(searchForm.value[item.field]) && searchForm.value[item.field].length > 0) {
        temp.push({
          label: item.props.label,
          value: searchForm.value[item.field].join(' ~ ')
        })
      } else if (item.type === 'input') {
        if (searchForm.value[item.field]) {
          temp.push({
            label: item.props.label,
            value: searchForm.value[item.field]
          })
        }
      } else if (item.type === 'select') {
        if (searchForm.value[item.field] || (Array.isArray(searchForm.value[item.field]) && searchForm.value[item.field].length > 0)) {
          temp.push({
            label: item.props.label,
            value: findText(searchForm.value[item.field], item.options)
          })
        }
      } else if (isObject(item.type)) {
        if (setSchemaFormRef.value.getCacheDataMap()[item.field]) {
          temp.push({
            label: item.props.label,
            value: setSchemaFormRef.value.getCacheDataMap()[item.field].map(item => item.name).join('、')
          })
        }
      } else if (item.type === 'slot') {
        if (Array.isArray(item.field) && item.field.length > 0) {
          const tempArr = []
          item.field.forEach(v => {
            if (searchForm.value[v]) {
              tempArr.push(searchForm.value[v] + (item.afterSuffix || ''))
            }
          })
          if (tempArr.length > 0) {
            console.log(tempArr)
            temp.push({
              label: item.props.label,
              value: tempArr.join(' ~ ')
            })
          }
        } else {
          temp.push({
            label: item.props.label,
            value: searchForm.value[item.field] + item.afterSuffix ? item.afterSuffix : ''
          })
        }
      }
    }
  })
  showList.value = temp
  nextTick(() => {
    checkLabel()
  })
  emit('search')
  searchWindowShow.value = false
}

function checkLabel() {
  let width = 38
  refs.value.forEach(item => {
    width += item.offsetWidth
  })
  if (width >= wrapWidth.value) {
    refs.value[refs.value.length - 1].remove()
    refs.value.splice(refs.value.length - 1, 1)
    showList.value.splice(showList.value.length - 1, 1)
    showMore.value = true
    checkLabel()
  }
}

function findText(data, list) {
  if (Array.isArray(data)) {
    return list.filter(item => data.includes(item.value)).map(item => item.label).join('、')
  } else {
    return list.find(item => data === item.value).label
  }
}

function clear() {
  searchForm.value = Object.assign({}, cacheForm.value)
  setSchemaFormRef.value.clearValidate()
  emit('clear')
}

function clearData() {
  searchForm.value = Object.assign({}, cacheForm.value)
  setSchemaFormRef.value.clearValidate()
  search()
}

function setDefault(data) {
  if (Array.isArray(data.cacheKey) && data.cacheKey.length > 0) {
    data.cacheKey.forEach(key => {
      cacheForm.value[key] = data[key]
    })
  }
  delete data.cacheKey
  Object.assign(searchForm.value, data)
  // search()
}

function getValue() {
  const temp = deepClone(searchForm.value)
  if (Array.isArray(temp.date) && temp.date.length > 0) {
    temp.beginDate = temp.date[0]
    temp.endDate = temp.date[1]
    delete temp.date
  }
  return temp
}

function close() {
  searchWindowShow.value = false
}

onMounted(() => {
  nextTick(() => {
    wrapWidth.value = labelWrap.value.offsetWidth - 40
  })
})

defineExpose({
  getValue,
  setDefault,
  init,
  close,
  clear,
  clearData
})
</script>

<style scoped lang="scss">
.search-wrap {
  padding-right: 30px;
  flex: 1;
  justify-content: flex-end;
  margin-left: 32px;
  .label-wrap {
    justify-content: flex-end;
    overflow: hidden;
    flex-wrap: nowrap;
    flex-shrink: 0;
  }
}
.form-item {
  background: #f5f7fa;
  border-radius: 4px;
  border: 1px solid #e6e6e6;
  height: 32px;
  font-size: $--font-size-min;
  padding: 0 8px;
  margin-right: 10px;
  line-height: 32px;
  white-space: nowrap;
}
.search-footer {
  display: flex;
  justify-content: flex-end;
  border-top: 1px dashed #dfdfdf;
  padding-top: 11px;
}
.dialog-search-wrap {
  &::v-deep(.el-input__inner),
  &::v-deep(.el-range-input),
  &::v-deep(.el-form-item__label) {
    font-size: 12px !important;
  }
}
</style>
